<template>
  <div class="terminal-wrap">

    <!-- 抽奖部分 -->
    <div class="lottery addLotteryLen" :style="{backgroundImage: 'url(' + descJson.homeJson.mainBgImage + ')' }">
      <div class="turnplate">
        <div class="realCanvas">
          <canvas ref="myCanvas" id="myCanvas" width="333" height="333"></canvas>
          <div class="pointer" @click="begin">
            <span :style="{background:descJson.homeJson.drawButtonColor}">
              点击
              <br />抽奖
            </span>
            <img class="point-image" src="/static/images/lottery/btn.png" alt />
          </div>
        </div>
      </div>
      <div class="count" v-if=" Number(consumeNum) == 0">今日免费抽奖次数：0</div>
      <div class="count" v-else-if=" Number(freeDrawNum) > 0">今日免费抽奖次数：{{ freeDrawNum }}</div>
      <div class="count" v-else >每次抽奖消耗{{ consumeNum }}积分</div>
      <div class="rule">
        <p class="tit">活动规则</p>
        <div class="rule-info">
          <pre v-html="activityRule" class="des"></pre>
        </div>
      </div>
    </div>


    <!-- 中奖页面 -->
    <div class="common-content" v-if="showWin">
      <div class="inner-content">
        <img :src="descJson.winningJson.bgImage" alt="" class="lotteryImage">

        <div class="wrap">
          <p class="title">中奖啦！</p>
          <img src="/static/images/close.png" alt="" class="close-image" @click.stop="close(1)">
          <img :src="winInfo.picUrl" alt="" class="prizeImage">
          <p class="level" v-if="winInfo.level == 1">一等奖</p>
          <p class="level" v-if="winInfo.level == 2">二等奖</p>
          <p class="level" v-if="winInfo.level == 3">三等奖</p>
          <p class="level" v-if="winInfo.level == 4">四等奖</p>
          <p class="level" v-if="winInfo.level == 5">五等奖</p>
          <p class="level" v-if="winInfo.level == 6">六等奖</p>
          <p class="level" v-if="winInfo.level == 7">七等奖</p>
          <p class="level" v-if="winInfo.level == 8">八等奖</p>
          <p class="level" v-if="winInfo.level == 9">九等奖</p>
          <p class="level" v-if="winInfo.level == 10">十等奖</p>

          <p class="name">{{ winInfo.awardsName }}</p>
          
          <div class="edit" v-if=" winInfo.awardsType == 2" @click="edit" :style="{background: descJson.winningJson.editUserInfoButtonColor}">编辑个人信息</div>
          <div class="edit" v-else @click="clickAgain(1)" :style="{background: descJson.winningJson.editUserInfoButtonColor}">再来一次</div>
        </div>

      </div>
    </div>

    <!-- 未中奖页面 -->
    <div class="common-content not-lottery" v-if="showLosing">
      <div class="inner-content">
        <img :src="descJson.noWinningJson.bgImage" alt="" class="lotteryImage">

        <div class="wrap">
          <p class="title">谢谢参与，再接再厉</p>
          <img src="/static/images/close.png" alt="" class="close-image" @click.stop="close(2)">
          <img :src="descJson.noWinningJson.noWinImage" alt="" class="prizeImage">
          <div class="edit" @click="clickAgain(2)" :style="{background: descJson.noWinningJson.aginButtonColor}">再来一次</div>
        </div>

      </div>
    </div>

    <!-- 编辑个人信息页面 -->
    <div class="common-content edit-content" v-if="showEdit">
      <div class="inner-content">
        <img :src="descJson.editUserInfoJson.bgImage" alt="" class="lotteryImage">

        <div class="wrap">
          <p class="title">编辑个人信息</p>
          <img src="/static/images/close.png" alt="" class="close-image" @click.stop="close(3)">

          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px" class="demo-ruleForm">
            <el-form-item  prop="name" :style="{background:descJson.editUserInfoJson.confirmButtonColor}">
              <span slot="label" class="label">姓名</span>
              <el-input v-model="ruleForm.name" placeholder="请输入真实姓名"></el-input>
            </el-form-item>

            <el-form-item prop="phone" :style="{background:descJson.editUserInfoJson.confirmButtonColor}">
              <span slot="label" class="label">手机号</span>
              <el-input v-model="ruleForm.phone" placeholder="请输入手机号" maxlength="11"></el-input>
            </el-form-item>

            <el-form-item prop="address" class="special" :style="{background:descJson.editUserInfoJson.confirmButtonColor}">
              <span slot="label" class="label">邮寄地址</span>
              <el-input type="textarea" v-model="ruleForm.address" placeholder="请输入邮寄地址"></el-input>
            </el-form-item>
            
            <div class="edit" @click="submitForm('ruleForm')" :style="{background:descJson.editUserInfoJson.confirmButtonColor}">确定</div>

          </el-form>
        </div>

      </div>
    </div>

    <!-- 手写toast -->
    <div class="toast-wrap" v-if="showToast">{{ toastMessage }}</div>
    
    
  </div>
</template>

<script>
  import $ from "@/assets/js/jquery.min.js";
  import { isEmail,isMobile } from "@/utils/validate";
  import turntable from "@/assets/js/turntable.js";
  export default {
    name: 'terminal',
    components: {
      
    },

    data() {
      return {                                                                                           
        // 编辑个人信息数据
        ruleForm: {
          name: '',
          phone: '',
          address: '',
        },
        // 编辑个人数据验证方法
        rules: {
          name: [
            { required: true, message: '请输入真实姓名', trigger: 'blur' },
            { min: 2, max: 5, message: '', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur' }
          ],
          address: [
            { required: true, message: '请输入邮寄地址', trigger: 'blur' }
          ],
        },

        // 大转盘中的按钮背景图样式
        descJson: {
          homeJson: {
            mainBgImage: require("../../../../../static/images/lottery/homeBg.png"),
            drawButtonColor: "#F86A63",
            turntableColor: "#e24b43"
          },
          winningJson: {
            editUserInfoButtonColor: "#F85037",
            winImage: require("../../../../../static/images/lottery/gift.png"),
            bgImage: require("../../../../../static/images/lottery/giftbg.png")
          },
          noWinningJson: {
            aginButtonColor: "#F85037",
            noWinImage: require("../../../../../static/images/lottery/thanks.png"),
            bgImage: require("../../../../../static/images/lottery/giftbg.png")
          },
          editUserInfoJson: {
            confirmButtonColor: "#F85037",
            bgImage: require("../../../../../static/images/lottery/giftbg.png")
          }
        },
        wheelSurf: "",   // 转盘
        list: [],
        isRequesting: false,                      // 是否正在请求接口（控制短时间内重复请求）
        freeDrawNum: 0,                           // 免费抽奖次数
        activityRule: '',                         // 活动规格
        drawResultCode: null,                     // 抽奖结果（1---中奖， 2---未中奖， 3---谢谢参与， 4---活动未开始， 5----活动已结束， 6----今日机会已用完， 7---抽奖机会已用完， 8---积分不足， 9----无订单， 10---活动不存在）
        showLosing: true,                        // 是否显示未中奖弹窗
        showWin: false,                           // 是否显示中奖弹窗
        showEdit: false,                          // 是否显示编辑个人信息弹窗
        winInfo:{},                               // 中奖商品信息
        receiveRecordId: '',                      // 中奖纪录ID
        consumeNum: 0,                            // 每次抽奖消耗积分数量
        accessToken: '',                          // 用户ID
        promotionCode: '',                        // 当前活动code
        toastMessage: '',                         // toast样式
        showToast: false,                         // 是否显示toast提示
        usableNum: 0,                             // 可抽奖数量（如果等于0，直接提示，不掉接口）
      }
    },

    created() {
      // 获取地址携带的参数 
      let params = this.$route.query;
      if(params.accessToken && params.accessToken != '' && params.accessToken != undefined && params.accessToken != null && params.promotionCode && params.promotionCode != '' && params.promotionCode != undefined && params.promotionCode != null) {
        this.accessToken = params.accessToken;
        this.promotionCode = params.promotionCode;
        // 获取抽奖活动数据
        this.getInfo();
      }else {
        this.showMessage('参数缺失');
      }

      
    },


    methods: {

      // 显示toast弹窗
      showMessage(value) {
        this.toastMessage = value;
        this.showToast = true;
        setTimeout(() => {
          this.showToast = false;
        },2000)
      },

      // 请求抽奖活动数据
      getInfo() {
        let params = {
          thirdUserId: this.accessToken,
          promotionCode: this.promotionCode,
        };
        this.utils.request.getLotteryInfo(params, res => {
          if (res.code == "0000") {
            
            this.freeDrawNum = res.data.freeDrawNum;      // 抽奖次数赋值
            this.consumeNum = res.data.consumeNum;        // 使用积分抽奖消耗数量
            this.activityRule = res.data.activityRule;    // 活动规则描述赋值
            this.usableNum = res.data.usableNum;          // 抽奖次数

            // 判断对象是否为空
            let data = res.data.pageDescJson;
            if(JSON.stringify(data) != "{}" && data != null) {
              this.descJson = res.data.pageDescJson;
            }
            if (res.data.awardsList && res.data.awardsList.length > 0) {
              this.angel = 360 / this.list.length;

              // 格式化成插件需要的奖品列表格式
              this.list = res.data.awardsList.map(m => {
                return {
                  id: m.id,
                  name: m.awardsRefName,
                  image: m.awardsPicUrl
                };
              });
              this.getAngel();
            }
          } else {
            this.showMessage(res.msg);
          }
        });
      },

      // 初始化大转盘数据
      getAngel() {
        // 清空画布
        var c = this.$refs["myCanvas"];
        var cxt = c.getContext("2d");
        c.height = c.height;
        let turntableColor = "";

        this.wheelSurf = turntable({
          myCanvas: this.$refs["myCanvas"],
          list: this.list, // 奖品 列表，(必填)
          outerCircle: {
            color: this.descJson.homeJson.turntableColor // 外圈颜色(可选)
          },
          innerCircle: {
            color: "#fff" // 里圈颜色(可选)
          },
          dots: ["#fff", "#fff7af"], // 装饰点颜色(可选)
          disk: [
            "#fcf9f0",
            "#fff7af",
            "#fcf9f0",
            "#fff7af",
            "#fcf9f0",
            "#fff7af",
            "#fcf9f0",
            "#fff7af",
            "#fcf9f0",
            "#fff7af",
            "#fcf9f0",
            "#fff7af"
          ], //中心奖盘的颜色，默认7彩(可选)
          title: {
            color: "#E34A44",
            font: "10px Arial"
          } // 奖品标题样式(可选)
        });
        this.wheelSurf.init();
      },

      // 点击再来一次触发方法
      clickAgain(value) {
        if(value == 1) {
          this.showWin = false;
        }else {
          this.showLosing = false;
        }
        
        this.begin();
      },

      // 点击编辑个人数据触发方法
      edit() {
        this.showWin = false;
        this.showEdit = true;
      },

      // 弹窗关闭按钮触发方法
      close(value) {
        if(value == 1) {
          this.showWin = false;
        }else if(value == 2) {
          this.showLosing = false;
        }else {
          this.showEdit = false;
        }
      },


      // 点击抽奖触发方法
      begin() {
        var that = this;

        if( this.usableNum == 0 ) {
          return that.showMessage('已达到今日抽奖次数上限，明天继续');
        }

        // 添加节流阀，防止短时间内联系点击
        if( that.isRequesting || that.list.length == 0) {
          return;
        };
        that.isRequesting = true;

        // 掉后台接口进行抽奖
        let params = {
          thirdUserId: that.accessToken,
          promotionCode: that.promotionCode,
        };
        that.utils.request.clickLottery(params, res => {
          if (res.code == "0000") {

            // 未中奖
            if(res.data.drawResultCode == 2) {

              // 旋转360度结束
              that.wheelSurf.lottery((360), function () {
                that.showLosing = true;
                that.isRequesting = false;
                that.getInfo();
              });
              
            }else if(res.data.drawResultCode == 1) {
              // 将返回的中奖数据进行赋值
              var winData = res.data.awardsVO;
              that.winInfo = res.data.awardsVO;
              that.receiveRecordId = res.data.receiveRecordId;
              var count = 0;
              var list = that.list;
              var angel = 360/that.list.length;   // 计算旋转角度
              for (const key in list) {
                if (list.hasOwnProperty(key)) {
                  if (winData.id == list[key].id) {
                    break;
                  }
                  count++
                }
              };

              // 转盘转动抽奖
              that.wheelSurf.lottery((count*angel + angel/2), function () {
                that.showWin = true;
                that.isRequesting = false;
                that.getInfo();
              });
            }else if(res.data.drawResultCode == 3){
              var winData = res.data.awardsVO;
              var count = 0;
              var list = that.list;
              var angel = 360/that.list.length;   // 计算旋转角度
              for (const key in list) {
                if (list.hasOwnProperty(key)) {
                  if (winData.id == list[key].id) {
                    break;
                  }
                  count++
                }
              };
              // 转盘转动抽奖
              that.wheelSurf.lottery((count*angel + angel/2), function () {
                that.showLosing = true;
                that.isRequesting = false;
                that.getInfo();
              });
            }else {
              that.isRequesting = false;
              that.showMessage(res.data.drawResultDesc);
              that.getInfo();
            }
          } else {
            that.isRequesting = false;
            that.showMessage(res.msg);
          }
        });
        
      },

      // 提交个人信息
      submitForm() {

        // 验证数据  提交接口  关闭弹窗
        if(this.ruleForm.name == '') {
          return this.showMessage('请输入真实姓名');
        }
        if(this.ruleForm.phone == '' || this.ruleForm.phone == null) {
          return this.showMessage('请输入手机号码');
        }
        if(!isMobile(this.ruleForm.phone)){
          return this.showMessage('请输入正确的手机号码');
        }
        if(this.ruleForm.address == '') {
          return this.showMessage('请输入邮寄地址');
        }

        let params = {
          thirdUserId: this.accessToken,
          promotionCode: this.promotionCode,
          name: this.ruleForm.name,
          mobile: this.ruleForm.phone,
          exactAddress: this.ruleForm.address,
          drawRecordRefId: this.receiveRecordId == null ? '' : this.receiveRecordId,
        };

        this.utils.request.saveAddress(params, res => {
          if (res.code == "0000") {
            this.showMessage('提交成功');
            this.showEdit = false;
          } else {
            this.showEdit = false;
            that.showMessage(res.msg);
          }
          this.ruleForm.name = "";
          this.ruleForm.phone = "";
          this.ruleForm.address = "";
        });
      },
    },
  }
</script>

<style lang="scss" scoped>
  /* 手写toast样式部分 */
  .toast-wrap {
    position: fixed;
    top: 30px;
    left: 50%;
    width: 220px;
    margin-left: -100px;
    height: 30px;
    line-height: 30px;
    background: rgba(0, 0, 0,.7);
    border-radius: 6px;
    text-align: center;
    font-size: 12px;
    color: #fff;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding: 0 10px;
    box-sizing: border-box;
  } 

  .terminal-wrap {
    width: 100%;
    height: auto;
    border: 1px solid #ccc;
    // border-radius: 10px;
    margin: 0 auto;
    overflow: hidden;
    position: relative;
  }
  .terminal {
    display: block;
    width: 100%;
    height: 100%;
    position: relative;
    .lotteryImage {
      display: block;
      width: 100%;
      height: 100%;
      margin: 0 auto;
      position: absolute;
      left: 0;
      top: 0;
    }
    .wrap {
      display: block;
      width: 100%;
      height: 100%;
      margin: 0 auto;
      position: absolute;
      left: 0;
      top: 140px;
      z-index: 999;
      .canvans-wrap {
        width: 300px;
        height: 300px;
        border: 1px solid #fff;
        margin: 0 auto;
      }
      .number-wrap {
        margin-top: 10px;
        color: #333333;
        font-size: 14px;
      }
      .rule-wrap {
        border: 1px dotted #333333;
        width: 80%;
        height: 150px;
        // overflow-y: scroll;
        margin: 20px auto;
        padding: 10px;
        box-sizing: border-box;
        border-top: 0 none;
        text-align: left;
        position: relative;
        .title {
          width: 100%;
          text-align: center;
          position: absolute;
          top: -8px;
          left: 0;
          &::before{
            content: '';
            color: #fff;
            display: inline-block;
            width: 40%;
            border-bottom: 1px dotted #333333;
            margin-bottom: 5px;
          }
          &::after{
            content: '';
            color: #fff;
            display: inline-block;
            width: 40%;
            border-bottom: 1px dotted #333333;
            margin-bottom: 5px;
          }
        }
      }

    }
  }
  .terminal-content {
    display: block;
    width: 100%;
    height: 100%;
  }
  /* 中奖 未中奖  编辑个人信息 公用样式 */ 
  .common-content {
    width: 100%;
    height: 100%;
    overflow: hidden;
    background: rgba(0,0,0,.7);
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    left: 0;
    .inner-content {
      width: 80%;
      height: 44%;
      text-align: center;
      border-radius: 10px;
      position: relative;
      .lotteryImage {
        display: block;
        width: 100%;
        height: 100%;
        margin: 0 auto;
        position: absolute;
        left: 0;
        top: 0;
      }
      .wrap {
        display: block;
        width: 100%;
        height: 100%;
        margin: 0 auto;
        position: absolute;
        left: 0;
        top: 0;
        z-index: 999;
        .title {
          color: #fff;
          font-size: 22px;
          margin: 25px 0 17px 0;
          z-index: 9;
          text-align: center;
        }
        .prizeImage {
          display: block;
          width: 150px;
          height: 166px;
          margin: 0 auto;
        }
        .close-image {
          position: absolute;
          display: block;
          width: 20px;
          height: 20px;
          top: 10px;
          right: 10px;
          cursor: pointer;
        }
        .level {
          color: #fff;
          font-size: 16px;
          margin-top: 10px;
        }
        .name {
          padding: 0 20px;
          box-sizing: border-box;
          color: #fff;
          font-size: 12px;
          margin-top: 5px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .edit {
          display: block;
          width: 66%;
          height: 32px;
          line-height: 32px;
          margin: 30px auto;
          text-align: center;
          background-color: #F85037;
          color: #fff;
          border-radius: 16px;
          cursor: pointer;
        }
      }
    }
  }

  /* 未中奖样式 */ 
  .not-lottery {
    .prizeImage {
      margin: 10px auto !important;
    }
    .edit {
      margin: 50px auto !important;
    }
  }

  /* 编辑个人信息样式 */ 
  .edit-content {
    .wrap {
      width: 100%;
      height: 100%;
      padding: 5% 0;
      box-sizing: border-box;
      .demo-ruleForm {
        padding: 0 20px;
        box-sizing: border-box;
      }
      /* element样式优化 */
      /deep/ .el-form-item {
        margin-bottom: 20px !important;
      }
      /deep/ .el-form-item__label {
        border-radius:4px 0px 0px 4px;
        color: #fff;
        padding-right: 5px;
        font-size: 12px;
      }
      /deep/  .el-form-item__label:before {
        color: #fff !important;
      }
      /deep/ .el-input__inner {
        border: 0 none !important;
        border-radius: 0 4px 4px 0 !important;
      }
      /deep/ .el-textarea__inner {
        border: 0 none !important;
        border-radius: 0 4px 4px 0 !important;
      }
      .special {
        /deep/ .el-form-item__label {
          height: 52px !important;
          line-height: 52px !important;
        }
      }
    }
  }



  /* 大转盘样式 */ 
  img {
    width: 100%;
    height: 100%;
  }

  .point-image {
    transform:rotate(-1deg);
  }
  .lottery {
    width: 375px;
    height: 600px;
    padding: 223px 0 0;
    position: relative;
    background-size: cover;
    color: #333;
    font-size: 14px;
    &.addLotteryLen {
      height: 640px;
    }
    .phone {
      width: 490px;
      position: absolute;
      top: -25px;
      left: -57px;
      z-index: 999;
    }
    .turnplate {
      width: 90%;
      margin: 0 5% 30px;
      position: relative;
      .realCanvas {
        height: 337.5px;
        .pointer {
          cursor: pointer;
          width: 86px;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          span {
            width: 60px;
            height: 60px;
            text-align: center;
            color: #fff;
            text-decoration: none;
            display: block;
            position: absolute;
            transform: translate(-50%, -50%);
            top: 50%;
            left: 50%;
            border-radius: 50%;
            margin-top: 3px;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 999;
          }
        }
      }
    }
    .count {
      padding: 10px;
      text-align: center;
    }
    .rule {
      margin: 5%;
      position: relative;
      border-left: 1px dashed #333;
      border-bottom: 1px dashed #333;
      border-right: 1px dashed #333;
      .rule-info {
        width: 95%;
        height: 150px;
        overflow-y: auto;
        padding: 0 0 20px 12px;
        line-height: 1.6;
        font-size: 12px;
        position: relative;
        z-index: 999;
        text-align: left;
        &::-webkit-scrollbar {
          width: 6px;
          height: 6px;
        }
        &::-webkit-scrollbar-thumb {
          background-color: rgba(255, 255, 255, 0.6);
          border-radius: 4px;
          margin-right: 2px;
        }
      }
      .tit {
        padding: 0 20px;
        display: inline-block;
        font-size: 16px;
        text-align: center;
        position: relative;
        top: -9px;
        left: 16%;
        transform: translateX(-50%);
        &::before,
        &::after {
          content: " ";
          position: absolute;
          top: 50%;
          width: 100px;
          height: 1px;
          border-top: 1px dashed #333;
        }
        &::before {
          left: -116px;
        }
        &::after {
          right: -116px;
        }
      }
      .des {
        font-size: 14px;
        white-space: pre-wrap;
        word-wrap: break-word;
        word-break: break-all;
      }
    }
    .box {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      background: rgba(0, 0, 0, 0.8);
      text-align: center;
    }
    .info {
      padding: 30px;
      width: 76%;
      min-height: 440px;
      background: url("/static/images/lottery/giftbg.png") no-repeat top center;
      background-size: cover;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      h3 {
        font-weight: normal;
        color: #fff;
        font-size: 30px;
      }
      .img {
        width: 130px;
        margin: 0 auto;
        padding: 30px 0;
      }
      /deep/ .el-button {
        margin: 0;
        background: #f35b5c;
        width: 90%;
        height: 64px !important;
        line-height: 64px !important;
        color: #fff;
        border: 0;
        border-radius: 64px;
        font-size: 26px !important;
      }
      .name {
        color: #333;
        font-size: 26px;
        margin-bottom: 20px;
        :first-child {
          font-size: 28px;
          margin-bottom: 12px;
        }
      }
    }
    .lotteryRuleForm {
      h3 {
        margin-bottom: 40px;
      }
      /deep/ .el-form-item {
        margin-bottom: 30px;
        .el-form-item__label {
          position: relative;
          height: 32px !important;
          .label{
            width: 84px;
            height: 32px !important;
            position: absolute;
            color: #fff;
            background: #f35b5c;
            border-radius:4px 0px 0px 4px; 
            text-align: center;
            line-height: 1.3 !important;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          
          &::before{
            color: #fff;
            position: absolute;
            top:50%;
            left: 10px;
            z-index: 99;
            transform: translateY(-50%);
          }
        }
        &:last-child{
          .el-form-item__label {
            height: 96px !important;
            .label{
              height: 96px !important;
            }
          }
        }
      }
    }
  }
</style>
